package com.lenin.omena.server;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.lenin.omena.shared.domain.Produce;
import com.lenin.omena.shared.domain.User;
import com.lenin.omena.shared.domain.UserInfo;

//@Repository("userDAO")
public class UserDAO extends JdoDAO<Long, User> {

	public UserDAO() {
		super();
	}
	
	public User getUserByUserName(String userName) {
		
		Query query = pm.newQuery(UserInfo.class);
		query.setFilter("userName == userNameParam");
		query.declareParameters("String userNameParam");
		
		List<UserInfo> infoList = (List<UserInfo>)query.execute(userName);
		
		User user = null;
		
		if(infoList.size() > 0) {
			UserInfo userInfo = infoList.get(0);
			query = pm.newQuery(User.class);
			query.setFilter("userInfo == userInfoParam");
			query.declareParameters("UserInfo userInfoParam");
			List<User> userList = (List<User>)query.execute(userInfo);
			if(userList.size() > 0)
				user = userList.get(0);
		}
		
		return user;
		
	}
	
	
	public void deleteProduce(User user, Produce produce) {
		
		
		Transaction tx = pm.currentTransaction();

		try
		{
		    tx.begin(); // Start the PM transaction

		    user.getSite().getProduce().remove(produce);
		    pm.makePersistent(user);
		    pm.deletePersistent(produce);
		    
		    tx.commit(); // Commit the PM transaction
		}
		finally
		{
		    if (tx.isActive())
		    {
		        tx.rollback(); // Error occurred so rollback the PM transaction
		    }
		}
		
	}
	


	public User addProduce(User user, Produce produce) {
		
		
		Transaction tx = pm.currentTransaction();

		User entity = null;
		
		try
		{
		    tx.begin(); // Start the PM transaction

		    user.getSite().getProduce().add(produce);
		    entity = pm.makePersistent(user);

		    tx.commit(); // Commit the PM transaction
		}
		finally
		{
		    if (tx.isActive())
		    {
		        tx.rollback(); // Error occurred so rollback the PM transaction
		    }
		}
		
		return entity;
		
		
	}
	
	
	public User setStatus(User user, Integer status) {
		
		Transaction tx = pm.currentTransaction();

		User entity = null;
		
		try
		{
		    tx.begin(); // Start the PM transaction

		    user.setStatus(status);
		    entity = pm.makePersistent(user);

		    tx.commit(); // Commit the PM transaction
		}
		finally
		{
		    if (tx.isActive())
		    {
		        tx.rollback(); // Error occurred so rollback the PM transaction
		    }
		}
		
		return entity;
		
		
	}
	
	
	
}
